package com.zongxingh.falcon.logger.utils;

import com.zongxingh.falcon.mq.utils.ExceptionTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Enumeration;

/**
 * Introduction:  <简介>
 * Package Name:  com.zongxingh.falcon.logger.utils
 * Project Name:  falcon-logger
 * Author:  zongxingh
 * Email： zongxingh@163.com
 * Tel: 157*****778
 * Create Time:  2020/10/27 10:52
 */
public class FalconUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(FalconUtil.class);
    private static final String LOCAL_LOOP = "127.0.0.1";

    public static String getServerIp(){
        String serverIp ="";
        // 根据网卡取本机配置的IP
        //定义网络接口枚举类
        Enumeration<NetworkInterface> allNetInterfaces;
        try {
            //获得网络接口
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            //遍历所有的网络接口
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                //同样再定义网络地址枚举类
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements())
                {
                    ip = addresses.nextElement();
                    if (ip instanceof Inet4Address)
                    {
                        if(!LOCAL_LOOP.equals(ip.getHostAddress())){
                            serverIp= ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            LOGGER.error("获得服务器端IP发生异常，异常信息：\n{}", ExceptionTools.getStackTraceAsString(e));
            return "";
        }
        return serverIp;
    }

    public static String getTimeStamp(String timestampFormat) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(timestampFormat);
        return dtf.format(now);
    }
}
